package com.example.show_auto.data

import android.content.Context
import android.content.SharedPreferences

/**
 * 应用设置存储管理器
 * 用于保存和加载应用的各种设置状态
 */
class SettingsStorage(context: Context) {
    
    private val sharedPreferences: SharedPreferences = 
        context.getSharedPreferences("app_settings", Context.MODE_PRIVATE)
    
    private val contextRef = context // 保存context引用，用于动态创建MultiUserDataManager
    
    companion object {
        private const val KEY_FILTER_OWNED_CHEFS = "filter_owned_chefs"
        private const val KEY_FILTER_OWNED_RECIPES = "filter_owned_recipes"
        private const val KEY_FILTER_AURA_CHEFS = "filter_aura_chefs"
        private const val KEY_FILTER_ULTIMATE_CHEFS = "filter_ultimate_chefs"
        private const val KEY_FILTER_NON_ULTIMATE_CHEFS = "filter_non_ultimate_chefs"
        private const val KEY_FILTER_UNOWNED_CHEFS = "filter_unowned_chefs" // 新增：查询未拥有厨师

    // 贵客率计算器筛选按钮状态
    private const val KEY_CALCULATOR_ONLY_SHOW_OWNED = "calculator_only_show_owned"
    private const val KEY_CALCULATOR_ONLY_SHOW_AURA_CHEFS = "calculator_only_show_aura_chefs"
    private const val KEY_CALCULATOR_ONLY_SHOW_ULTIMATE_CHEFS = "calculator_only_show_ultimate_chefs"
    private const val KEY_CALCULATOR_ONLY_SHOW_ASSASSIN_CHEFS = "calculator_only_show_assassin_chefs"
    // 心法盘默认满级设置
    private const val KEY_CALCULATOR_DEFAULT_MAX_LEVEL_AMBER = "calculator_default_max_level_amber"
    // 默认全修炼设置
    private const val KEY_CALCULATOR_DEFAULT_ALL_ULTIMATE = "calculator_default_all_ultimate"
    // 制作时间默认设置
    private const val KEY_CALCULATOR_DEFAULT_TIME = "calculator_default_time"
    // 查询模式设置
    private const val KEY_CALCULATOR_QUERY_MODE = "calculator_query_mode"
    // 使用个人数据设置
    private const val KEY_CALCULATOR_USE_PERSONAL_DATA = "calculator_use_personal_data"
    // 使用全部厨师设置
    private const val KEY_CALCULATOR_USE_ALL_CHEFS = "calculator_use_all_chefs"

    private const val KEY_LAST_CHECK_TIME = "last_check_time" // 上次检查更新时间
    private const val KEY_FORCE_UPDATE_PENDING = "force_update_pending" // 是否有待处理的强制更新
        private const val KEY_EQUIP_FILTER_SKILL = "equip_filter_skill"
        private const val KEY_EQUIP_FILTER_RARITY1 = "equip_filter_rarity1"
        private const val KEY_EQUIP_FILTER_RARITY2 = "equip_filter_rarity2"
        private const val KEY_EQUIP_FILTER_RARITY3 = "equip_filter_rarity3"
        private const val KEY_RECIPE_FILTER_RARITY1 = "recipe_filter_rarity1"
        private const val KEY_RECIPE_FILTER_RARITY2 = "recipe_filter_rarity2"
        private const val KEY_RECIPE_FILTER_RARITY3 = "recipe_filter_rarity3"
        private const val KEY_RECIPE_FILTER_RARITY4 = "recipe_filter_rarity4"
        private const val KEY_RECIPE_FILTER_RARITY5 = "recipe_filter_rarity5"
        private const val KEY_SELECTED_AURA_CHEFS = "selected_aura_chefs"
    private const val KEY_SELECTED_QUERY_CHEFS = "selected_query_chefs"
        private const val KEY_USE_POWERFUL_EQUIPS = "use_powerful_equips"
        private const val KEY_USE_UNOWNED_RECIPES = "use_unowned_recipes"
        private const val KEY_PREFER_SHORTER_TIME_RECIPES = "prefer_shorter_time_recipes"
        private const val KEY_THEME_MODE = "theme_mode"
        private const val KEY_SHOW_GOLD_RUNES = "show_gold_runes"
        private const val KEY_SHOW_SILVER_RUNES = "show_silver_runes"
        private const val KEY_SHOW_BRONZE_RUNES = "show_bronze_runes"
        private const val KEY_SHOW_GOLD_RUNES_FOR_GOD_RUNE = "show_gold_runes_for_god_rune"
        private const val KEY_SHOW_SILVER_RUNES_FOR_GOD_RUNE = "show_silver_runes_for_god_rune"
        private const val KEY_SHOW_BRONZE_RUNES_FOR_GOD_RUNE = "show_bronze_runes_for_god_rune"
        // 菜谱选择对话框符文筛选状态
        private const val KEY_RECIPE_FILTER_GOLD_RUNES = "recipe_filter_gold_runes"
        private const val KEY_RECIPE_FILTER_SILVER_RUNES = "recipe_filter_silver_runes"
        private const val KEY_RECIPE_FILTER_BRONZE_RUNES = "recipe_filter_bronze_runes"
        private const val KEY_VEG_AREA_ORDER = "veg_area_order"
        private const val KEY_JADE_AREA_ORDER = "jade_area_order"
        private const val KEY_COND_AREA_ORDER = "cond_area_order"
        private const val KEY_LAB_AREA_ORDER = "lab_area_order"
        private const val KEY_ENABLE_JADE_AREA = "enable_jade_area"
        private const val KEY_ENABLE_VEG_AREA = "enable_veg_area"
        private const val KEY_ENABLE_COND_AREA = "enable_cond_area"
        private const val KEY_ENABLE_LAB_AREA = "enable_lab_area"
    
    // 菜地配置人数和采集点持久化（添加用户ID支持）
    private const val KEY_VEG_AREA_PEOPLE_PREFIX = "veg_area_people_"
    private const val KEY_VEG_AREA_CAPACITY_PREFIX = "veg_area_capacity_"

    // 玉片区配置人数和采集点持久化（添加用户ID支持）
    private const val KEY_JADE_AREA_PEOPLE_PREFIX = "jade_area_people_"
    private const val KEY_JADE_AREA_CAPACITY_PREFIX = "jade_area_capacity_"

    // 调料区配置人数和采集点持久化（添加用户ID支持）
    private const val KEY_COND_AREA_PEOPLE_PREFIX = "cond_area_people_"
    private const val KEY_COND_AREA_CAPACITY_PREFIX = "cond_area_capacity_"

    // 实验室配置人数和采集点持久化（添加用户ID支持）
    private const val KEY_LAB_AREA_PEOPLE_PREFIX = "lab_area_people_"
    private const val KEY_LAB_AREA_CAPACITY_PREFIX = "lab_area_capacity_"

    // 统一区域排序设置（跨区域拖拽排序）
    private const val KEY_UNIFIED_AREA_ORDER = "unified_area_order"

    // 顶部三项配置顺序（jade|veg|cond）
    private const val KEY_CONFIG_SECTION_ORDER = "config_section_order"
    
    // 符文菜谱数量持久化
    private const val KEY_GOLD_RUNE_RECIPE_COUNTS = "gold_rune_recipe_counts"
    private const val KEY_SILVER_RUNE_RECIPE_COUNTS = "silver_rune_recipe_counts"
    private const val KEY_BRONZE_RUNE_RECIPE_COUNTS = "bronze_rune_recipe_counts"
    
    // 符文选择状态持久化
    private const val KEY_GOLD_RUNE_SELECTIONS = "gold_rune_selections"
    private const val KEY_SILVER_RUNE_SELECTIONS = "silver_rune_selections"
    private const val KEY_BRONZE_RUNE_SELECTIONS = "bronze_rune_selections"
    
    // 符文下拉框展开状态持久化
    private const val KEY_GOLD_RUNE_EXPANDED = "gold_rune_expanded"
    private const val KEY_SILVER_RUNE_EXPANDED = "silver_rune_expanded"
    private const val KEY_BRONZE_RUNE_EXPANDED = "bronze_rune_expanded"
    }
    
    /**
     * 动态获取当前用户ID
     */
    private fun getCurrentUserId(): String? {
        val multiUserDataManager = MultiUserDataManager(contextRef)
        return multiUserDataManager.getCurrentUserId()
    }
    
    /**
     * 生成带用户ID的键名
     */
    private fun getKeyWithUserId(baseKey: String): String {
        val userId = getCurrentUserId()
        return if (userId != null) {
            "${baseKey}_${userId}"
        } else {
            baseKey // 如果没有用户ID，使用原始键名（向后兼容）
        }
    }
    
    /**
     * 保存过滤设置
     */
    fun saveFilterSettings(filterOwnedChefs: Boolean, filterOwnedRecipes: Boolean) {
        sharedPreferences.edit().apply {
            putBoolean(KEY_FILTER_OWNED_CHEFS, filterOwnedChefs)
            putBoolean(KEY_FILTER_OWNED_RECIPES, filterOwnedRecipes)
            apply()
        }
    }
    
    /**
     * 获取过滤厨师设置
     */
    fun getFilterOwnedChefs(): Boolean {
        return sharedPreferences.getBoolean(KEY_FILTER_OWNED_CHEFS, true) // 默认开启
    }
    
    /**
     * 获取过滤菜谱设置
     */
    fun getFilterOwnedRecipes(): Boolean {
        return sharedPreferences.getBoolean(KEY_FILTER_OWNED_RECIPES, true) // 默认开启
    }
    
    /**
     * 保存单个厨师过滤设置
     */
    fun saveFilterOwnedChefs(enabled: Boolean) {
        sharedPreferences.edit().apply {
            putBoolean(KEY_FILTER_OWNED_CHEFS, enabled)
            apply()
        }
    }
    
    /**
     * 保存单个菜谱过滤设置
     */
    fun saveFilterOwnedRecipes(enabled: Boolean) {
        sharedPreferences.edit().apply {
            putBoolean(KEY_FILTER_OWNED_RECIPES, enabled)
            apply()
        }
    }
    
    // 厨具筛选设置
    
    /**
     * 保存厨具技法筛选设置
     */
    fun saveEquipFilterSkill(enabled: Boolean) {
        sharedPreferences.edit().apply {
            putBoolean(KEY_EQUIP_FILTER_SKILL, enabled)
            apply()
        }
    }
    
    /**
     * 获取厨具技法筛选设置
     */
    fun getEquipFilterSkill(): Boolean {
        return sharedPreferences.getBoolean(KEY_EQUIP_FILTER_SKILL, false)
    }
    
    /**
     * 保存厨具星级筛选设置
     */
    fun saveEquipFilterRarity(rarity1: Boolean, rarity2: Boolean, rarity3: Boolean) {
        sharedPreferences.edit().apply {
            putBoolean(KEY_EQUIP_FILTER_RARITY1, rarity1)
            putBoolean(KEY_EQUIP_FILTER_RARITY2, rarity2)
            putBoolean(KEY_EQUIP_FILTER_RARITY3, rarity3)
            apply()
        }
    }
    
    /**
     * 获取1星厨具筛选设置
     */
    fun getEquipFilterRarity1(): Boolean {
        return sharedPreferences.getBoolean(KEY_EQUIP_FILTER_RARITY1, false)
    }
    
    /**
     * 获取2星厨具筛选设置
     */
    fun getEquipFilterRarity2(): Boolean {
        return sharedPreferences.getBoolean(KEY_EQUIP_FILTER_RARITY2, false)
    }
    
    /**
     * 获取3星厨具筛选设置
     */
    fun getEquipFilterRarity3(): Boolean {
        return sharedPreferences.getBoolean(KEY_EQUIP_FILTER_RARITY3, false)
    }

    // 光环厨师筛选设置

    /**
     * 保存光环厨师筛选设置
     */
    fun saveFilterAuraChefs(enabled: Boolean) {
        sharedPreferences.edit().apply {
            putBoolean(KEY_FILTER_AURA_CHEFS, enabled)
            apply()
        }
    }

    /**
     * 获取光环厨师筛选设置
     */
    fun getFilterAuraChefs(): Boolean {
        return sharedPreferences.getBoolean(KEY_FILTER_AURA_CHEFS, false) // 默认关闭
    }

    // 已修炼厨师筛选设置

    /**
     * 保存已修炼厨师筛选设置
     */
    fun saveFilterUltimateChefs(enabled: Boolean) {
        sharedPreferences.edit().apply {
            putBoolean(KEY_FILTER_ULTIMATE_CHEFS, enabled)
            apply()
        }
    }

    /**
     * 获取已修炼厨师筛选设置
     */
    fun getFilterUltimateChefs(): Boolean {
        return sharedPreferences.getBoolean(KEY_FILTER_ULTIMATE_CHEFS, false) // 默认关闭
    }

    /**
     * 保存未修炼厨师筛选设置
     */
    fun saveFilterNonUltimateChefs(enabled: Boolean) {
        with(sharedPreferences.edit()) {
            putBoolean(KEY_FILTER_NON_ULTIMATE_CHEFS, enabled)
            apply()
        }
    }

    /**
     * 获取未修炼厨师筛选设置
     */
    fun getFilterNonUltimateChefs(): Boolean {
        return sharedPreferences.getBoolean(KEY_FILTER_NON_ULTIMATE_CHEFS, false) // 默认关闭
    }

    /**
     * 保存查询未拥有厨师筛选设置
     */
    fun saveFilterUnownedChefs(enabled: Boolean) {
        with(sharedPreferences.edit()) {
            putBoolean(KEY_FILTER_UNOWNED_CHEFS, enabled)
            apply()
        }
    }

    /**
     * 获取查询未拥有厨师筛选设置
     */
    fun getFilterUnownedChefs(): Boolean {
        return sharedPreferences.getBoolean(KEY_FILTER_UNOWNED_CHEFS, false) // 默认关闭
    }

    // 菜谱星级筛选设置

    /**
     * 保存菜谱星级筛选设置
     */
    fun saveRecipeFilterRarity(rarity1: Boolean, rarity2: Boolean, rarity3: Boolean, rarity4: Boolean, rarity5: Boolean) {
        sharedPreferences.edit().apply {
            putBoolean(KEY_RECIPE_FILTER_RARITY1, rarity1)
            putBoolean(KEY_RECIPE_FILTER_RARITY2, rarity2)
            putBoolean(KEY_RECIPE_FILTER_RARITY3, rarity3)
            putBoolean(KEY_RECIPE_FILTER_RARITY4, rarity4)
            putBoolean(KEY_RECIPE_FILTER_RARITY5, rarity5)
            apply()
        }
    }

    /**
     * 获取1星菜谱筛选设置
     */
    fun getRecipeFilterRarity1(): Boolean {
        return sharedPreferences.getBoolean(KEY_RECIPE_FILTER_RARITY1, false)
    }

    /**
     * 获取2星菜谱筛选设置
     */
    fun getRecipeFilterRarity2(): Boolean {
        return sharedPreferences.getBoolean(KEY_RECIPE_FILTER_RARITY2, false)
    }

    /**
     * 获取3星菜谱筛选设置
     */
    fun getRecipeFilterRarity3(): Boolean {
        return sharedPreferences.getBoolean(KEY_RECIPE_FILTER_RARITY3, false)
    }

    /**
     * 获取4星菜谱筛选设置
     */
    fun getRecipeFilterRarity4(): Boolean {
        return sharedPreferences.getBoolean(KEY_RECIPE_FILTER_RARITY4, false)
    }

    /**
     * 获取5星菜谱筛选设置
     */
    fun getRecipeFilterRarity5(): Boolean {
        return sharedPreferences.getBoolean(KEY_RECIPE_FILTER_RARITY5, false)
    }

    /**
     * 根据任务要求设置菜谱星级筛选（一键查询专用）
     */
    fun setRecipeFilterForQuest(taskRarity: Int) {
        saveRecipeFilterRarity(
            rarity1 = taskRarity == 1,
            rarity2 = taskRarity == 2,
            rarity3 = taskRarity == 3,
            rarity4 = taskRarity == 4,
            rarity5 = taskRarity == 5
        )
    }

    // 光环厨师选择状态

    /**
     * 保存所有光环厨师名称集合（用于持久化光环厨师列表）
     */
    fun saveAllAuraChefNames(allChefNames: Set<String>) {
        val chefsString = allChefNames.joinToString(",")
        sharedPreferences.edit().apply {
            putString("${KEY_SELECTED_AURA_CHEFS}_all_names", chefsString)
            apply()
        }
    }

    /**
     * 获取所有光环厨师名称集合（从持久化存储中读取）
     */
    fun getAllAuraChefNames(): Set<String> {
        val chefsString = sharedPreferences.getString("${KEY_SELECTED_AURA_CHEFS}_all_names", "")
        return if (chefsString.isNullOrEmpty()) {
            emptySet()
        } else {
            chefsString.split(",").toSet()
        }
    }

    /**
     * 检查是否已经保存过所有光环厨师名称
     */
    fun hasAllAuraChefNamesBeenSaved(): Boolean {
        return sharedPreferences.contains("${KEY_SELECTED_AURA_CHEFS}_all_names")
    }

    /**
     * 保存选中的光环厨师名称集合
     */
    fun saveSelectedAuraChefs(selectedChefs: Set<String>) {
        val chefsString = selectedChefs.joinToString(",")
        sharedPreferences.edit().apply {
            putString(KEY_SELECTED_AURA_CHEFS, chefsString)
            apply()
        }
    }

    /**
     * 获取选中的光环厨师名称集合
     */
    fun getSelectedAuraChefs(): Set<String> {
        val chefsString = sharedPreferences.getString(KEY_SELECTED_AURA_CHEFS, "")
        return if (chefsString.isNullOrEmpty()) {
            emptySet()
        } else {
            chefsString.split(",").toSet()
        }
    }

    /**
     * 检查是否已经设置过光环厨师选择（区分从未设置和主动清空）
     */
    fun hasSelectedAuraChefsBeenSet(): Boolean {
        return sharedPreferences.contains(KEY_SELECTED_AURA_CHEFS)
    }

    // 查询厨师选择状态
    /**
     * 保存选择参与查询的厨师列表
     */
    fun saveSelectedQueryChefs(selectedChefs: Set<String>) {
        val chefsString = selectedChefs.joinToString(",")
        sharedPreferences.edit()
            .putString(KEY_SELECTED_QUERY_CHEFS, chefsString)
            .apply()
    }

    /**
     * 获取选择参与查询的厨师列表
     */
    fun getSelectedQueryChefs(): Set<String> {
        val chefsString = sharedPreferences.getString(KEY_SELECTED_QUERY_CHEFS, "")
        return if (chefsString.isNullOrEmpty()) {
            emptySet()
        } else {
            chefsString.split(",").toSet()
        }
    }

    /**
     * 检查是否已经设置过查询厨师选择（区分从未设置和主动清空）
     */
    fun hasQueryChefsBeenSet(): Boolean {
        return sharedPreferences.contains(KEY_SELECTED_QUERY_CHEFS)
    }

    /**
     * 保存是否使用强力厨具设置
     */
    fun saveUsePowerfulEquips(usePowerfulEquips: Boolean) {
        sharedPreferences.edit().apply {
            putBoolean(KEY_USE_POWERFUL_EQUIPS, usePowerfulEquips)
            apply()
        }
    }

    /**
     * 获取是否使用强力厨具设置
     */
    fun getUsePowerfulEquips(): Boolean {
        return sharedPreferences.getBoolean(KEY_USE_POWERFUL_EQUIPS, true) // 默认启用
    }

    /**
     * 保存是否使用未拥有菜谱设置
     */
    fun saveUseUnownedRecipes(useUnownedRecipes: Boolean) {
        sharedPreferences.edit().apply {
            putBoolean(KEY_USE_UNOWNED_RECIPES, useUnownedRecipes)
            apply()
        }
    }

    /**
     * 获取是否使用未拥有菜谱设置
     */
    fun getUseUnownedRecipes(): Boolean {
        return sharedPreferences.getBoolean(KEY_USE_UNOWNED_RECIPES, true) // 默认启用
    }

    /**
     * 保存是否优先使用时间较短菜谱设置
     */
    fun savePreferShorterTimeRecipes(preferShorterTimeRecipes: Boolean) {
        sharedPreferences.edit().apply {
            putBoolean(KEY_PREFER_SHORTER_TIME_RECIPES, preferShorterTimeRecipes)
            apply()
        }
    }

    /**
     * 获取是否优先使用时间较短菜谱设置
     */
    fun getPreferShorterTimeRecipes(): Boolean {
        return sharedPreferences.getBoolean(KEY_PREFER_SHORTER_TIME_RECIPES, false) // 默认关闭
    }



    /**
     * 保存主题模式设置
     * @param themeMode 主题模式：0=跟随系统，1=浅色，2=深色
     */
    fun saveThemeMode(themeMode: Int) {
        sharedPreferences.edit().apply {
            putInt(KEY_THEME_MODE, themeMode)
            apply()
        }
    }

    /**
     * 获取主题模式设置
     * @return 主题模式：0=跟随系统，1=浅色，2=深色
     */
    fun getThemeMode(): Int {
        return sharedPreferences.getInt(KEY_THEME_MODE, 0) // 默认跟随系统
    }



    /**
     * 保存上次检查更新时间
     */
    fun saveLastCheckTime(timestamp: Long) {
        with(sharedPreferences.edit()) {
            putLong(KEY_LAST_CHECK_TIME, timestamp)
            apply()
        }
    }

    /**
     * 获取上次检查更新时间
     */
    fun getLastCheckTime(): Long {
        return sharedPreferences.getLong(KEY_LAST_CHECK_TIME, 0L)
    }

    // 强制更新状态管理
    /**
     * 设置强制更新待处理状态
     */
    fun setForceUpdatePending(pending: Boolean) {
        with(sharedPreferences.edit()) {
            putBoolean(KEY_FORCE_UPDATE_PENDING, pending)
            apply()
        }
    }

    /**
     * 检查是否有待处理的强制更新
     */
    fun hasForceUpdatePending(): Boolean {
        return sharedPreferences.getBoolean(KEY_FORCE_UPDATE_PENDING, false)
    }

    /**
     * 清除强制更新状态（更新完成后调用）
     */
    fun clearForceUpdatePending() {
        setForceUpdatePending(false)
    }

    // 符文筛选按钮状态管理

    /**
     * 保存符文筛选按钮状态
     */
    fun saveRuneFilterStates(showGold: Boolean, showSilver: Boolean, showBronze: Boolean) {
        sharedPreferences.edit().apply {
            putBoolean(KEY_SHOW_GOLD_RUNES, showGold)
            putBoolean(KEY_SHOW_SILVER_RUNES, showSilver)
            putBoolean(KEY_SHOW_BRONZE_RUNES, showBronze)
            apply()
        }
    }

    /**
     * 获取金符文筛选状态
     */
    fun getShowGoldRunes(): Boolean {
        return sharedPreferences.getBoolean(KEY_SHOW_GOLD_RUNES, false)
    }

    /**
     * 获取银符文筛选状态
     */
    fun getShowSilverRunes(): Boolean {
        return sharedPreferences.getBoolean(KEY_SHOW_SILVER_RUNES, false)
    }

    /**
     * 获取铜符文筛选状态
     */
    fun getShowBronzeRunes(): Boolean {
        return sharedPreferences.getBoolean(KEY_SHOW_BRONZE_RUNES, false)
    }

    /**
     * 保存神级符文碰瓷筛选状态
     */
    fun saveGodRuneFilterStates(showGold: Boolean, showSilver: Boolean, showBronze: Boolean) {
        sharedPreferences.edit().apply {
            putBoolean(KEY_SHOW_GOLD_RUNES_FOR_GOD_RUNE, showGold)
            putBoolean(KEY_SHOW_SILVER_RUNES_FOR_GOD_RUNE, showSilver)
            putBoolean(KEY_SHOW_BRONZE_RUNES_FOR_GOD_RUNE, showBronze)
            apply()
        }
    }

    /**
     * 获取神级符文碰瓷金符文筛选状态
     */
    fun getShowGoldRunesForGodRune(): Boolean {
        return sharedPreferences.getBoolean(KEY_SHOW_GOLD_RUNES_FOR_GOD_RUNE, false)
    }

    /**
     * 获取神级符文碰瓷银符文筛选状态
     */
    fun getShowSilverRunesForGodRune(): Boolean {
        return sharedPreferences.getBoolean(KEY_SHOW_SILVER_RUNES_FOR_GOD_RUNE, false)
    }

    /**
     * 获取神级符文碰瓷铜符文筛选状态
     */
    fun getShowBronzeRunesForGodRune(): Boolean {
        return sharedPreferences.getBoolean(KEY_SHOW_BRONZE_RUNES_FOR_GOD_RUNE, false)
    }

    // 菜谱选择对话框符文筛选状态管理

    /**
     * 保存菜谱选择对话框符文筛选状态
     */
    fun saveRecipeFilterRuneStates(showGold: Boolean, showSilver: Boolean, showBronze: Boolean) {
        sharedPreferences.edit().apply {
            putBoolean(KEY_RECIPE_FILTER_GOLD_RUNES, showGold)
            putBoolean(KEY_RECIPE_FILTER_SILVER_RUNES, showSilver)
            putBoolean(KEY_RECIPE_FILTER_BRONZE_RUNES, showBronze)
            apply()
        }
    }

    /**
     * 获取菜谱选择对话框金符文筛选状态
     */
    fun getRecipeFilterGoldRunes(): Boolean {
        return sharedPreferences.getBoolean(KEY_RECIPE_FILTER_GOLD_RUNES, false)
    }

    /**
     * 获取菜谱选择对话框银符文筛选状态
     */
    fun getRecipeFilterSilverRunes(): Boolean {
        return sharedPreferences.getBoolean(KEY_RECIPE_FILTER_SILVER_RUNES, false)
    }

    /**
     * 获取菜谱选择对话框铜符文筛选状态
     */
    fun getRecipeFilterBronzeRunes(): Boolean {
        return sharedPreferences.getBoolean(KEY_RECIPE_FILTER_BRONZE_RUNES, false)
    }

    /**
     * 保存菜地区采集优先级顺序（以逗号分隔）
     */
    fun saveVegAreaOrder(order: List<String>) {
        val value = order.joinToString(",")
        val key = getKeyWithUserId(KEY_VEG_AREA_ORDER)
        sharedPreferences.edit().apply {
            putString(key, value)
            apply()
        }
    }

    /**
     * 获取菜地区采集优先级顺序
     */
    fun getVegAreaOrder(): List<String> {
        val key = getKeyWithUserId(KEY_VEG_AREA_ORDER)
        val stored = sharedPreferences.getString(key, null)
        return if (stored.isNullOrEmpty()) emptyList() else stored.split(",")
    }

    /**
     * 保存玉片区采集优先级顺序（以逗号分隔）
     */
    fun saveJadeAreaOrder(order: List<String>) {
        val value = order.joinToString(",")
        val key = getKeyWithUserId(KEY_JADE_AREA_ORDER)
        sharedPreferences.edit().apply {
            putString(key, value)
            apply()
        }
    }

    /**
     * 获取玉片区采集优先级顺序
     */
    fun getJadeAreaOrder(): List<String> {
        val key = getKeyWithUserId(KEY_JADE_AREA_ORDER)
        val stored = sharedPreferences.getString(key, null)
        return if (stored.isNullOrEmpty()) emptyList() else stored.split(",")
    }

    /**
     * 保存调料区采集优先级顺序（以逗号分隔）
     */
    fun saveCondAreaOrder(order: List<String>) {
        val value = order.joinToString(",")
        val key = getKeyWithUserId(KEY_COND_AREA_ORDER)
        sharedPreferences.edit().apply {
            putString(key, value)
            apply()
        }
    }

    /**
     * 获取调料区采集优先级顺序
     */
    fun getCondAreaOrder(): List<String> {
        val key = getKeyWithUserId(KEY_COND_AREA_ORDER)
        val stored = sharedPreferences.getString(key, null)
        return if (stored.isNullOrEmpty()) emptyList() else stored.split(",")
    }

    // 区域开关
    fun saveEnableJadeArea(enabled: Boolean) {
        val key = getKeyWithUserId(KEY_ENABLE_JADE_AREA)
        sharedPreferences.edit().apply {
            putBoolean(key, enabled)
            apply()
        }
        
        if (!enabled) {
            // 如果关闭玉片区，从统一排序中移除所有玉片区地区
            cleanUnifiedAreaOrderByPrefix("jade_")
        } else {
            // 如果开启玉片区，将玉片区地区加入统一排序
            addJadeAreasToUnifiedOrder()
        }
    }
    fun getEnableJadeArea(): Boolean {
        val key = getKeyWithUserId(KEY_ENABLE_JADE_AREA)
        return sharedPreferences.getBoolean(key, true)
    }
    fun saveEnableVegArea(enabled: Boolean) {
        val key = getKeyWithUserId(KEY_ENABLE_VEG_AREA)
        sharedPreferences.edit().apply {
            putBoolean(key, enabled)
            apply()
        }
        
        if (!enabled) {
            // 如果关闭菜地区，从统一排序中移除所有菜地区地区
            cleanUnifiedAreaOrderByPrefix("veg_")
        } else {
            // 如果开启菜地区，将菜地区地区加入统一排序
            addVegAreasToUnifiedOrder()
        }
    }
    fun getEnableVegArea(): Boolean {
        val key = getKeyWithUserId(KEY_ENABLE_VEG_AREA)
        return sharedPreferences.getBoolean(key, true)
    }
    fun saveEnableCondArea(enabled: Boolean) {
        val key = getKeyWithUserId(KEY_ENABLE_COND_AREA)
        sharedPreferences.edit().apply {
            putBoolean(key, enabled)
            apply()
        }
        
        if (!enabled) {
            // 如果关闭调料区，从统一排序中移除所有调料区地区
            cleanUnifiedAreaOrderByPrefix("cond_")
        } else {
            // 如果开启调料区，将调料区地区加入统一排序
            addCondAreasToUnifiedOrder()
        }
    }
    fun getEnableCondArea(): Boolean {
        val key = getKeyWithUserId(KEY_ENABLE_COND_AREA)
        return sharedPreferences.getBoolean(key, true)
    }
    fun saveEnableLabArea(enabled: Boolean) {
        val key = getKeyWithUserId(KEY_ENABLE_LAB_AREA)
        sharedPreferences.edit().apply {
            putBoolean(key, enabled)
            apply()
        }
        
        if (!enabled) {
            // 如果关闭实验室，从统一排序中移除所有实验室地区
            cleanUnifiedAreaOrderByPrefix("lab_")
        } else {
            // 如果开启实验室，将实验室地区加入统一排序
            addLabAreasToUnifiedOrder()
        }
    }
    fun getEnableLabArea(): Boolean {
        val key = getKeyWithUserId(KEY_ENABLE_LAB_AREA)
        return sharedPreferences.getBoolean(key, false) // 默认为false，新功能
    }
    
    /**
     * 保存菜地区域特定项目的人数配置
     */
    fun saveVegAreaPeople(areaName: String, people: Int) {
        val key = getKeyWithUserId(KEY_VEG_AREA_PEOPLE_PREFIX + areaName)
        sharedPreferences.edit().apply {
            putInt(key, people)
            apply()
        }
    }
    
    /**
     * 获取菜地区域特定项目的人数配置
     */
    fun getVegAreaPeople(areaName: String): Int {
        val key = getKeyWithUserId(KEY_VEG_AREA_PEOPLE_PREFIX + areaName)
        return sharedPreferences.getInt(key, 5) // 默认值改为5
    }
    
    /**
     * 保存菜地区域特定项目的采集点配置
     */
    fun saveVegAreaCapacity(areaName: String, capacity: Int) {
        val key = getKeyWithUserId(KEY_VEG_AREA_CAPACITY_PREFIX + areaName)
        sharedPreferences.edit().apply {
            putInt(key, capacity)
            apply()
        }
    }
    
    /**
     * 获取菜地区域特定项目的采集点配置
     */
    fun getVegAreaCapacity(areaName: String, defaultCapacity: Int): Int {
        val key = getKeyWithUserId(KEY_VEG_AREA_CAPACITY_PREFIX + areaName)
        return sharedPreferences.getInt(key, defaultCapacity)
    }

    /**
     * 保存玉片区域特定项目的人数配置
     */
    fun saveJadeAreaPeople(areaName: String, people: Int) {
        val key = getKeyWithUserId(KEY_JADE_AREA_PEOPLE_PREFIX + areaName)
        sharedPreferences.edit().apply {
            putInt(key, people)
            apply()
        }
    }

    /**
     * 获取玉片区域特定项目的人数配置（默认5）
     */
    fun getJadeAreaPeople(areaName: String): Int {
        val key = getKeyWithUserId(KEY_JADE_AREA_PEOPLE_PREFIX + areaName)
        return sharedPreferences.getInt(key, 5)
    }

    /**
     * 保存玉片区域特定项目的采集点配置
     */
    fun saveJadeAreaCapacity(areaName: String, capacity: Int) {
        val key = getKeyWithUserId(KEY_JADE_AREA_CAPACITY_PREFIX + areaName)
        sharedPreferences.edit().apply {
            putInt(key, capacity)
            apply()
        }
    }

    /**
     * 获取玉片区域特定项目的采集点配置（默认60）
     */
    fun getJadeAreaCapacity(areaName: String, defaultCapacity: Int = 60): Int {
        val key = getKeyWithUserId(KEY_JADE_AREA_CAPACITY_PREFIX + areaName)
        return sharedPreferences.getInt(key, defaultCapacity)
    }

    /**
     * 保存调料区域特定项目的人数配置
     */
    fun saveCondAreaPeople(areaName: String, people: Int) {
        val key = getKeyWithUserId(KEY_COND_AREA_PEOPLE_PREFIX + areaName)
        sharedPreferences.edit().apply {
            putInt(key, people)
            apply()
        }
    }

    /**
     * 获取调料区域特定项目的人数配置（默认5）
     */
    fun getCondAreaPeople(areaName: String): Int {
        val key = getKeyWithUserId(KEY_COND_AREA_PEOPLE_PREFIX + areaName)
        return sharedPreferences.getInt(key, 5)
    }

    /**
     * 保存调料区域特定项目的采集点配置
     */
    fun saveCondAreaCapacity(areaName: String, capacity: Int) {
        val key = getKeyWithUserId(KEY_COND_AREA_CAPACITY_PREFIX + areaName)
        sharedPreferences.edit().apply {
            putInt(key, capacity)
            apply()
        }
    }

    /**
     * 获取调料区域特定项目的采集点配置（默认60）
     */
    fun getCondAreaCapacity(areaName: String, defaultCapacity: Int = 60): Int {
        val key = getKeyWithUserId(KEY_COND_AREA_CAPACITY_PREFIX + areaName)
        return sharedPreferences.getInt(key, defaultCapacity)
    }

    /**
     * 保存实验室区域特定项目的人数配置
     */
    fun saveLabAreaPeople(areaName: String, people: Int) {
        val key = getKeyWithUserId(KEY_LAB_AREA_PEOPLE_PREFIX + areaName)
        sharedPreferences.edit().apply {
            putInt(key, people)
            apply()
        }
    }

    /**
     * 获取实验室区域特定项目的人数配置（默认5）
     */
    fun getLabAreaPeople(areaName: String): Int {
        val key = getKeyWithUserId(KEY_LAB_AREA_PEOPLE_PREFIX + areaName)
        return sharedPreferences.getInt(key, 5)
    }

    /**
     * 保存实验室区域特定项目的采集点配置
     */
    fun saveLabAreaCapacity(areaName: String, capacity: Int) {
        val key = getKeyWithUserId(KEY_LAB_AREA_CAPACITY_PREFIX + areaName)
        sharedPreferences.edit().apply {
            putInt(key, capacity)
            apply()
        }
    }

    /**
     * 获取实验室区域特定项目的采集点配置（默认60）
     */
    fun getLabAreaCapacity(areaName: String, defaultCapacity: Int = 60): Int {
        val key = getKeyWithUserId(KEY_LAB_AREA_CAPACITY_PREFIX + areaName)
        return sharedPreferences.getInt(key, defaultCapacity)
    }

    /**
     * 保存实验室区域顺序
     */
    fun saveLabAreaOrder(orderNames: List<String>) {
        val value = orderNames.joinToString(",")
        val key = getKeyWithUserId(KEY_LAB_AREA_ORDER)
        sharedPreferences.edit().apply {
            putString(key, value)
            apply()
        }
    }

    /**
     * 获取实验室区域顺序
     */
    fun getLabAreaOrder(): List<String> {
        val key = getKeyWithUserId(KEY_LAB_AREA_ORDER)
        val stored = sharedPreferences.getString(key, null)
        return if (stored.isNullOrEmpty()) emptyList() else stored.split(",")
    }

    // 顶部三项配置顺序存取
    fun saveConfigSectionOrder(orderIds: List<String>) {
        val value = orderIds.joinToString(",")
        val key = getKeyWithUserId(KEY_CONFIG_SECTION_ORDER)
        sharedPreferences.edit().apply {
            putString(key, value)
            apply()
        }
    }
    fun getConfigSectionOrder(): List<String> {
        val key = getKeyWithUserId(KEY_CONFIG_SECTION_ORDER)
        val stored = sharedPreferences.getString(key, null)
        return if (stored.isNullOrEmpty()) emptyList() else stored.split(",")
    }

    // ==================== 贵客率计算器筛选按钮状态 ====================
    
    /**
     * 保存贵客率计算器筛选按钮状态
     */
    fun saveCalculatorFilterStates(
        onlyShowOwned: Boolean,
        onlyShowAuraChefs: Boolean,
        onlyShowUltimateChefs: Boolean,
        onlyShowAssassinChefs: Boolean
    ) {
        sharedPreferences.edit().apply {
            putBoolean(getKeyWithUserId(KEY_CALCULATOR_ONLY_SHOW_OWNED), onlyShowOwned)
            putBoolean(getKeyWithUserId(KEY_CALCULATOR_ONLY_SHOW_AURA_CHEFS), onlyShowAuraChefs)
            putBoolean(getKeyWithUserId(KEY_CALCULATOR_ONLY_SHOW_ULTIMATE_CHEFS), onlyShowUltimateChefs)
            putBoolean(getKeyWithUserId(KEY_CALCULATOR_ONLY_SHOW_ASSASSIN_CHEFS), onlyShowAssassinChefs)
            apply()
        }
    }
    
    /**
     * 获取贵客率计算器"查询已有"按钮状态
     */
    fun getCalculatorOnlyShowOwned(): Boolean {
        val key = getKeyWithUserId(KEY_CALCULATOR_ONLY_SHOW_OWNED)
        return sharedPreferences.getBoolean(key, true)  // 默认显示已有厨师
    }
    
    /**
     * 获取贵客率计算器"查询贵客"按钮状态
     */
    fun getCalculatorOnlyShowAuraChefs(): Boolean {
        val key = getKeyWithUserId(KEY_CALCULATOR_ONLY_SHOW_AURA_CHEFS)
        return sharedPreferences.getBoolean(key, false)
    }
    
    /**
     * 获取贵客率计算器"查询已修炼"按钮状态
     */
    fun getCalculatorOnlyShowUltimateChefs(): Boolean {
        val key = getKeyWithUserId(KEY_CALCULATOR_ONLY_SHOW_ULTIMATE_CHEFS)
        return sharedPreferences.getBoolean(key, false)
    }
    
    /**
     * 获取贵客率计算器"查询刺客"按钮状态
     */
    fun getCalculatorOnlyShowAssassinChefs(): Boolean {
        val key = getKeyWithUserId(KEY_CALCULATOR_ONLY_SHOW_ASSASSIN_CHEFS)
        return sharedPreferences.getBoolean(key, false)
    }
    
    /**
     * 保存心法盘默认满级设置
     */
    fun saveCalculatorDefaultMaxLevelAmber(enabled: Boolean) {
        val key = getKeyWithUserId(KEY_CALCULATOR_DEFAULT_MAX_LEVEL_AMBER)
        sharedPreferences.edit().apply {
            putBoolean(key, enabled)
            apply()
        }
    }
    
    /**
     * 获取心法盘默认满级设置
     */
    fun getCalculatorDefaultMaxLevelAmber(): Boolean {
        val key = getKeyWithUserId(KEY_CALCULATOR_DEFAULT_MAX_LEVEL_AMBER)
        return sharedPreferences.getBoolean(key, false) // 默认关闭
    }
    
    /**
     * 保存默认全修炼设置
     */
    fun saveCalculatorDefaultAllUltimate(enabled: Boolean) {
        val key = getKeyWithUserId(KEY_CALCULATOR_DEFAULT_ALL_ULTIMATE)
        sharedPreferences.edit().apply {
            putBoolean(key, enabled)
            apply()
        }
    }
    
    /**
     * 获取默认全修炼设置
     */
    fun getCalculatorDefaultAllUltimate(): Boolean {
        val key = getKeyWithUserId(KEY_CALCULATOR_DEFAULT_ALL_ULTIMATE)
        return sharedPreferences.getBoolean(key, false) // 默认关闭
    }
    
    /**
     * 保存制作时间默认设置
     */
    fun saveCalculatorDefaultTime(time: Float) {
        val key = getKeyWithUserId(KEY_CALCULATOR_DEFAULT_TIME)
        sharedPreferences.edit().apply {
            putFloat(key, time)
            apply()
        }
    }
    
    /**
     * 获取制作时间默认设置
     */
    fun getCalculatorDefaultTime(): Float {
        val key = getKeyWithUserId(KEY_CALCULATOR_DEFAULT_TIME)
        return try {
            // 尝试获取Float值
            sharedPreferences.getFloat(key, 7.0f)
        } catch (e: Exception) {
            // 如果Float获取失败，尝试获取Int值（兼容旧版本）
            try {
                val intValue = sharedPreferences.getInt(key, 7)
                // 将Int转换为Float并保存，实现数据迁移
                val floatValue = intValue.toFloat()
                saveCalculatorDefaultTime(floatValue)
                floatValue
            } catch (e2: Exception) {
                // 如果都失败，使用默认值
                7.0f
            }
        }
    }
    
    /**
     * 保存查询模式设置
     */
    fun saveCalculatorQueryMode(enabled: Boolean) {
        val key = getKeyWithUserId(KEY_CALCULATOR_QUERY_MODE)
        sharedPreferences.edit().apply {
            putBoolean(key, enabled)
            apply()
        }
    }
    
    /**
     * 获取查询模式设置
     */
    fun getCalculatorQueryMode(): Boolean {
        val key = getKeyWithUserId(KEY_CALCULATOR_QUERY_MODE)
        return sharedPreferences.getBoolean(key, false) // 默认关闭（查询必来）
    }
    
    /**
     * 保存使用个人数据设置
     */
    fun saveCalculatorUsePersonalData(enabled: Boolean) {
        val key = getKeyWithUserId(KEY_CALCULATOR_USE_PERSONAL_DATA)
        sharedPreferences.edit().apply {
            putBoolean(key, enabled)
            apply()
        }
    }
    
    /**
     * 获取使用个人数据设置
     */
    fun getCalculatorUsePersonalData(): Boolean {
        val key = getKeyWithUserId(KEY_CALCULATOR_USE_PERSONAL_DATA)
        return sharedPreferences.getBoolean(key, true) // 默认开启
    }
    
    /**
     * 保存使用全部厨师设置
     */
    fun saveCalculatorUseAllChefs(enabled: Boolean) {
        val key = getKeyWithUserId(KEY_CALCULATOR_USE_ALL_CHEFS)
        sharedPreferences.edit().apply {
            putBoolean(key, enabled)
            apply()
        }
    }
    
    /**
     * 获取使用全部厨师设置
     */
    fun getCalculatorUseAllChefs(): Boolean {
        val key = getKeyWithUserId(KEY_CALCULATOR_USE_ALL_CHEFS)
        return sharedPreferences.getBoolean(key, false) // 默认关闭
    }
    
    // ==================== 符文菜谱数量和选择状态持久化 ====================
    
    /**
     * 保存金符文菜谱数量
     */
    fun saveGoldRuneRecipeCounts(counts: Map<String, Int>) {
        val key = getKeyWithUserId(KEY_GOLD_RUNE_RECIPE_COUNTS)
        val jsonString = counts.entries.joinToString(",") { "${it.key}:${it.value}" }
        sharedPreferences.edit().putString(key, jsonString).apply()
    }
    
    /**
     * 获取金符文菜谱数量
     */
    fun getGoldRuneRecipeCounts(): Map<String, Int> {
        val key = getKeyWithUserId(KEY_GOLD_RUNE_RECIPE_COUNTS)
        val jsonString = sharedPreferences.getString(key, "") ?: ""
        return if (jsonString.isNotEmpty()) {
            jsonString.split(",").associate { pair: String ->
                val parts = pair.split(":")
                if (parts.size == 2) {
                    parts[0] to (parts[1].toIntOrNull() ?: 0)
                } else {
                    "" to 0
                }
            }.filter { it.key.isNotEmpty() }
        } else {
            emptyMap()
        }
    }
    
    /**
     * 保存银符文菜谱数量
     */
    fun saveSilverRuneRecipeCounts(counts: Map<String, Int>) {
        val key = getKeyWithUserId(KEY_SILVER_RUNE_RECIPE_COUNTS)
        val jsonString = counts.entries.joinToString(",") { "${it.key}:${it.value}" }
        sharedPreferences.edit().putString(key, jsonString).apply()
    }
    
    /**
     * 获取银符文菜谱数量
     */
    fun getSilverRuneRecipeCounts(): Map<String, Int> {
        val key = getKeyWithUserId(KEY_SILVER_RUNE_RECIPE_COUNTS)
        val jsonString = sharedPreferences.getString(key, "") ?: ""
        return if (jsonString.isNotEmpty()) {
            jsonString.split(",").associate { pair: String ->
                val parts = pair.split(":")
                if (parts.size == 2) {
                    parts[0] to (parts[1].toIntOrNull() ?: 0)
                } else {
                    "" to 0
                }
            }.filter { it.key.isNotEmpty() }
        } else {
            emptyMap()
        }
    }
    
    /**
     * 保存铜符文菜谱数量
     */
    fun saveBronzeRuneRecipeCounts(counts: Map<String, Int>) {
        val key = getKeyWithUserId(KEY_BRONZE_RUNE_RECIPE_COUNTS)
        val jsonString = counts.entries.joinToString(",") { "${it.key}:${it.value}" }
        sharedPreferences.edit().putString(key, jsonString).apply()
    }
    
    /**
     * 获取铜符文菜谱数量
     */
    fun getBronzeRuneRecipeCounts(): Map<String, Int> {
        val key = getKeyWithUserId(KEY_BRONZE_RUNE_RECIPE_COUNTS)
        val jsonString = sharedPreferences.getString(key, "") ?: ""
        return if (jsonString.isNotEmpty()) {
            jsonString.split(",").associate { pair: String ->
                val parts = pair.split(":")
                if (parts.size == 2) {
                    parts[0] to (parts[1].toIntOrNull() ?: 0)
                } else {
                    "" to 0
                }
            }.filter { it.key.isNotEmpty() }
        } else {
            emptyMap()
        }
    }
    
    /**
     * 保存金符文选择状态
     */
    fun saveGoldRuneSelections(selections: Set<String>) {
        val key = getKeyWithUserId(KEY_GOLD_RUNE_SELECTIONS)
        val jsonString = selections.joinToString(",")
        sharedPreferences.edit().putString(key, jsonString).apply()
    }
    
    /**
     * 获取金符文选择状态
     */
    fun getGoldRuneSelections(): Set<String> {
        val key = getKeyWithUserId(KEY_GOLD_RUNE_SELECTIONS)
        val jsonString = sharedPreferences.getString(key, "") ?: ""
        return if (jsonString.isNotEmpty()) {
            jsonString.split(",").toSet()
        } else {
            emptySet()
        }
    }
    
    /**
     * 保存银符文选择状态
     */
    fun saveSilverRuneSelections(selections: Set<String>) {
        val key = getKeyWithUserId(KEY_SILVER_RUNE_SELECTIONS)
        val jsonString = selections.joinToString(",")
        sharedPreferences.edit().putString(key, jsonString).apply()
    }
    
    /**
     * 获取银符文选择状态
     */
    fun getSilverRuneSelections(): Set<String> {
        val key = getKeyWithUserId(KEY_SILVER_RUNE_SELECTIONS)
        val jsonString = sharedPreferences.getString(key, "") ?: ""
        return if (jsonString.isNotEmpty()) {
            jsonString.split(",").toSet()
        } else {
            emptySet()
        }
    }
    
    /**
     * 保存铜符文选择状态
     */
    fun saveBronzeRuneSelections(selections: Set<String>) {
        val key = getKeyWithUserId(KEY_BRONZE_RUNE_SELECTIONS)
        val jsonString = selections.joinToString(",")
        sharedPreferences.edit().putString(key, jsonString).apply()
    }
    
    /**
     * 获取铜符文选择状态
     */
    fun getBronzeRuneSelections(): Set<String> {
        val key = getKeyWithUserId(KEY_BRONZE_RUNE_SELECTIONS)
        val jsonString = sharedPreferences.getString(key, "") ?: ""
        return if (jsonString.isNotEmpty()) {
            jsonString.split(",").toSet()
        } else {
            emptySet() 
        }
    }
    
    // ==================== 符文下拉框展开状态持久化 ====================
    
    /**
     * 保存金符文下拉框展开状态
     */
    fun saveGoldRuneExpanded(expanded: Boolean) {
        val key = getKeyWithUserId(KEY_GOLD_RUNE_EXPANDED)
        sharedPreferences.edit().putBoolean(key, expanded).apply()
    }
    
    /**
     * 获取金符文下拉框展开状态
     */
    fun getGoldRuneExpanded(): Boolean {
        val key = getKeyWithUserId(KEY_GOLD_RUNE_EXPANDED)
        return sharedPreferences.getBoolean(key, false) // 默认收起
    }
    
    /**
     * 保存银符文下拉框展开状态
     */
    fun saveSilverRuneExpanded(expanded: Boolean) {
        val key = getKeyWithUserId(KEY_SILVER_RUNE_EXPANDED)
        sharedPreferences.edit().putBoolean(key, expanded).apply()
    }
    
    /**
     * 获取银符文下拉框展开状态
     */
    fun getSilverRuneExpanded(): Boolean {
        val key = getKeyWithUserId(KEY_SILVER_RUNE_EXPANDED)
        return sharedPreferences.getBoolean(key, false) // 默认收起
    }
    
    /**
     * 保存铜符文下拉框展开状态
     */
    fun saveBronzeRuneExpanded(expanded: Boolean) {
        val key = getKeyWithUserId(KEY_BRONZE_RUNE_EXPANDED)
        sharedPreferences.edit().putBoolean(key, expanded).apply()
    }
    
    /**
     * 获取铜符文下拉框展开状态
     */
    fun getBronzeRuneExpanded(): Boolean {
        val key = getKeyWithUserId(KEY_BRONZE_RUNE_EXPANDED)
        return sharedPreferences.getBoolean(key, false) // 默认收起
    }
    
    /**
     * 保存统一区域排序（跨区域拖拽排序）
     */
    fun saveUnifiedAreaOrder(orderList: List<String>) {
        val key = getKeyWithUserId(KEY_UNIFIED_AREA_ORDER)
        val orderString = orderList.joinToString(",")
        sharedPreferences.edit().putString(key, orderString).apply()
    }
    
    /**
     * 获取统一区域排序
     */
    fun getUnifiedAreaOrder(): List<String> {
        val key = getKeyWithUserId(KEY_UNIFIED_AREA_ORDER)
        val orderString = sharedPreferences.getString(key, "") ?: ""
        return if (orderString.isNotEmpty()) {
            orderString.split(",").filter { it.isNotEmpty() }
        } else {
            emptyList()
        }
    }
    
    /**
     * 从统一排序中移除指定前缀的所有地区
     */
    private fun cleanUnifiedAreaOrderByPrefix(prefix: String) {
        val currentOrder = getUnifiedAreaOrder()
        val cleanedOrder = currentOrder.filter { !it.startsWith(prefix) }
        
        if (cleanedOrder != currentOrder) {
            saveUnifiedAreaOrder(cleanedOrder)
            println("DEBUG: 设置保存 - 从统一排序中移除${prefix}前缀的地区")
            println("DEBUG: 设置保存 - 清理前: $currentOrder")
            println("DEBUG: 设置保存 - 清理后: $cleanedOrder")
        }
    }
    
    /**
     * 将菜地区地区添加到统一排序
     */
    private fun addVegAreasToUnifiedOrder() {
        val vegAreas = listOf("池塘", "菜棚", "菜地", "森林", "牧场", "猪圈", "鸡舍", "作坊")
        val vegAreaIds = vegAreas.map { "veg_$it" }
        addAreasToUnifiedOrder(vegAreaIds, "菜地区")
    }
    
    /**
     * 将玉片区地区添加到统一排序
     */
    private fun addJadeAreasToUnifiedOrder() {
        val jadeAreas = listOf("藏心亭", "朝阴山", "北冥城", "清空谷", "还寒洞", "永昼宫")
        val jadeAreaIds = jadeAreas.map { "jade_$it" }
        addAreasToUnifiedOrder(jadeAreaIds, "玉片区")
    }
    
    /**
     * 将调料区地区添加到统一排序
     */
    private fun addCondAreasToUnifiedOrder() {
        val condAreas = listOf("樊正阁", "庖丁阁", "膳祖阁", "易牙阁", "彭铿阁", "伊尹阁")
        val condAreaIds = condAreas.map { "cond_$it" }
        addAreasToUnifiedOrder(condAreaIds, "调料区")
    }
    
    /**
     * 将实验室地区添加到统一排序
     */
    private fun addLabAreasToUnifiedOrder() {
        // 实验室地区暂时为空，等待后续添加
        val labAreas = listOf<String>()
        val labAreaIds = labAreas.map { "lab_$it" }
        addAreasToUnifiedOrder(labAreaIds, "实验室")
    }
    
    /**
     * 通用方法：将地区列表添加到统一排序末尾
     */
    private fun addAreasToUnifiedOrder(areaIds: List<String>, areaTypeName: String) {
        if (areaIds.isEmpty()) return
        
        val currentOrder = getUnifiedAreaOrder()
        val newAreas = areaIds.filter { it !in currentOrder } // 只添加不存在的地区
        
        if (newAreas.isNotEmpty()) {
            val updatedOrder = currentOrder + newAreas
            saveUnifiedAreaOrder(updatedOrder)
            println("DEBUG: 设置保存 - 开启${areaTypeName}，添加地区到统一排序")
            println("DEBUG: 设置保存 - 添加前: $currentOrder")
            println("DEBUG: 设置保存 - 添加后: $updatedOrder")
            println("DEBUG: 设置保存 - 新增地区: $newAreas")
        }
    }

    // 银布鞋设置
    private val KEY_USE_SILVER_SHOES = "use_silver_shoes"

    /**
     * 保存是否默认使用银布鞋设置
     */
    fun saveUseSilverShoes(useSilverShoes: Boolean) {
        sharedPreferences.edit()
            .putBoolean(KEY_USE_SILVER_SHOES, useSilverShoes)
            .apply()
    }

    /**
     * 获取是否默认使用银布鞋设置
     */
    fun getUseSilverShoes(): Boolean {
        return sharedPreferences.getBoolean(KEY_USE_SILVER_SHOES, false)
    }

    // 满级心法盘设置
    private val KEY_USE_MAX_LEVEL_AMBER = "use_max_level_amber"

    /**
     * 保存是否默认使用满级心法盘设置
     */
    fun saveUseMaxLevelAmber(useMaxLevelAmber: Boolean) {
        sharedPreferences.edit()
            .putBoolean(KEY_USE_MAX_LEVEL_AMBER, useMaxLevelAmber)
            .apply()
    }

    /**
     * 获取是否默认使用满级心法盘设置
     */
    fun getUseMaxLevelAmber(): Boolean {
        return sharedPreferences.getBoolean(KEY_USE_MAX_LEVEL_AMBER, false)
    }

    // 玉片区银布鞋设置
    private val KEY_USE_JADE_SILVER_SHOES = "use_jade_silver_shoes"

    /**
     * 保存玉片区是否默认使用银布鞋设置
     */
    fun saveUseJadeSilverShoes(useSilverShoes: Boolean) {
        sharedPreferences.edit()
            .putBoolean(KEY_USE_JADE_SILVER_SHOES, useSilverShoes)
            .apply()
    }

    /**
     * 获取玉片区是否默认使用银布鞋设置
     */
    fun getUseJadeSilverShoes(): Boolean {
        return sharedPreferences.getBoolean(KEY_USE_JADE_SILVER_SHOES, false)
    }

    // 玉片区满级心法盘设置（采集点加成类型）
    private val KEY_USE_JADE_MAX_LEVEL_AMBER = "use_jade_max_level_amber"

    /**
     * 保存玉片区是否默认使用满级心法盘设置
     */
    fun saveUseJadeMaxLevelAmber(useMaxLevelAmber: Boolean) {
        sharedPreferences.edit()
            .putBoolean(KEY_USE_JADE_MAX_LEVEL_AMBER, useMaxLevelAmber)
            .apply()
    }

    /**
     * 获取玉片区是否默认使用满级心法盘设置
     */
    fun getUseJadeMaxLevelAmber(): Boolean {
        return sharedPreferences.getBoolean(KEY_USE_JADE_MAX_LEVEL_AMBER, false)
    }
    
    // 全修炼开关设置
    private val KEY_USE_ALL_ULTIMATE_TRAINING = "use_all_ultimate_training"
    
    /**
     * 保存是否开启全修炼模式（所有厨师默认为已修炼状态）
     */
    fun saveUseAllUltimateTraining(enabled: Boolean) {
        sharedPreferences.edit().putBoolean(KEY_USE_ALL_ULTIMATE_TRAINING, enabled).apply()
    }

    /**
     * 获取是否开启全修炼模式
     */
    fun getUseAllUltimateTraining(): Boolean {
        return sharedPreferences.getBoolean(KEY_USE_ALL_ULTIMATE_TRAINING, false)
    }
    
    // 实验室配置设置
    private val KEY_USE_LAB_EQUIP_150 = "use_lab_equip_150"
    private val KEY_USE_BEGINNER_EQUIP_100 = "use_beginner_equip_100"
    
    /**
     * 保存是否默认使用实验室150厨具设置
     */
    fun saveUseLabEquip150(useLabEquip150: Boolean) {
        sharedPreferences.edit()
            .putBoolean(KEY_USE_LAB_EQUIP_150, useLabEquip150)
            .apply()
    }
    
    /**
     * 获取是否默认使用实验室150厨具设置
     */
    fun getUseLabEquip150(): Boolean {
        return sharedPreferences.getBoolean(KEY_USE_LAB_EQUIP_150, false)
    }
    
    /**
     * 保存是否默认使用新手100厨具设置
     */
    fun saveUseBeginnerEquip100(useBeginnerEquip100: Boolean) {
        sharedPreferences.edit()
            .putBoolean(KEY_USE_BEGINNER_EQUIP_100, useBeginnerEquip100)
            .apply()
    }
    
    /**
     * 获取是否默认使用新手100厨具设置
     */
    fun getUseBeginnerEquip100(): Boolean {
        return sharedPreferences.getBoolean(KEY_USE_BEGINNER_EQUIP_100, false)
    }
}